package com.fengjue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengjue.common.RespBean;
import com.fengjue.pojo.Menu;
import com.fengjue.pojo.MenuRole;
import com.fengjue.pojo.Role;
import com.fengjue.service.IMenuRoleService;
import com.fengjue.service.IMenuService;
import com.fengjue.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/basic/permission")
public class PermissController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IMenuRoleService menuRoleService;


    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }


    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public RespBean addRole(@RequestBody Role role){
        if(!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if (roleService.save(role)){
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败！");
    }

//    @ApiOperation(value = "更新角色")
//    @PutMapping("/")
//    public RespBean updateRole(@RequestBody Role role){
//        if (roleService.updateById(role)){
//            return RespBean.success("更新成功！");
//        }
//        return RespBean.error("更新失败！");
//    }

    @ApiOperation(value = "单条删除角色")
    @DeleteMapping("/role/{id}")
    public RespBean deleteRole(@PathVariable Integer id){
        if (roleService.removeById(id)){
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }

    @ApiOperation(value = "批量删除角色")
    @DeleteMapping("/")
    public RespBean deleteRolesByIds(Integer[] ids){
        if (roleService.removeByIds(Arrays.asList(ids))){
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }


    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }

    @ApiOperation(value = "根据角色id查询菜单id集合")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable("rid") Integer id){
        return menuRoleService.list(new QueryWrapper<MenuRole>(
        ).eq("rid",id)
        ).stream().map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping
    public RespBean updateRole(Integer rid,Integer[] mids){
        System.out.println("rid = " + rid);
        System.out.println("mids = " + mids);
        return menuRoleService.updateMenuRole(rid,mids);
    }
}
